/*
 * 文件名：FeeBillServiceImpl.java 描述： 修改人：Administrator 修改时间：2016年4月19日 跟踪单号： 修改单号： 修改内容：
 */

package com.zcsy.manage.service.property.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.base.CellUnit;
import com.zcsy.manage.model.property.FeeBill;
import com.zcsy.manage.model.property.FeeBillConfig;
import com.zcsy.manage.model.property.FeeBillDetail;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.property.FeeBillDao;
import com.zcsy.manage.persistence.property.FeeBillDetailDao;
import com.zcsy.manage.persistence.system.DictDao;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.property.IFeeBillService;

/**
 * @Title: FeeBillServiceImpl.java
 * @Package： com.zcsy.manage.service.property.impl
 * @Description: 物业缴费记录服务层实现类
 * @author xujl
 * @Copyright: 2016 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月19日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Service
public class FeeBillServiceImpl implements IFeeBillService {

    @Autowired
    private FeeBillDao dao;
    
    @Autowired
    private FeeBillDetailDao detailDao;
    
    @Autowired
    private ICellRegionService cellRegionService;
    
    @Autowired
    private ICellBuildingService cellBuildingService;
    
    @Autowired
    private ICellUnitService cellUnitService;
    
    @Autowired
    private ICellHouseService cellHouseService;

    @Autowired
    private DictDao dictDao;
    
    private static final int NO_BILL  =  0;  //不要发票
    private static final int PERSON_BILL  =  1;  //个人
    private static final int COMPANY_BILL  =  2;  //单位
//    private static final int ERROR_FALSE  =  0;  //无错误
//    private static final int ERROR_TRUE  =  0;  //有错误

    @Override
    public int insert(FeeBill record) {
        return dao.insert(record);
    }

    @Override
    public int updateByPrimaryKey(FeeBill record) {
        return dao.updateByPrimaryKey(record);
    }

    @Override
    public int deleteByPrimaryKey(String id) {
        return dao.deleteByPrimaryKey(id);
    }

    @Override
    public FeeBill selectByPrimaryKey(String id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    public List<FeeBill> selectByKeyword(FeeBill record) {
        return dao.selectByKeyword(record);
    }

    @Override
	public List<FeeBillDetail> selectFeeBillByHouseId(List<String> housesID){
		return dao.selectFeeBillByHouseId(housesID);
	}
    
    @Override
	public List<FeeBillDetail> getWyBillRecord(List<String> housesID){
		return dao.getWyBillRecord(housesID);
	}
    
    @Override
	public FeeBill getFeeBillInfo(String billID){
		return dao.getFeeBillInfo(billID);
	}
    
    @Override
    public int importFeeBill(List<List> list, String cellId,User user) {
        Date nowDate = DateUtils.getDate();
        int flag = Constants.SQL_RESULT_ERROR;
        String name ="";
        
        if (CollectionUtils.isNotEmpty(list)) {
            // 获取网优中心会审的信息
            for (List result : list) {
                @SuppressWarnings("unchecked")
                ArrayList<String> obj = (ArrayList<String>) result;
                
                CellHouse house = new CellHouse();
                house.setCellId(cellId);
                house.setRegionName((String) result.get(2));
                house.setBuildingName((String) result.get(3));
                house.setUnitName((String) result.get(4));
                name = (String) result.get(5);
                name = name.substring(0,name.indexOf("."));
                house.setName(name);
                List<CellHouse> houseList = cellHouseService.selectForImport(house);
                house = houseList.get(0);
                
                FeeBill bill = new FeeBill();
                bill.setCellId(cellId.toString());
                bill.setHouseId(house.getId());
                bill.setId(UniqueNumberUtils.get18UniqueNumber());
                bill.setSendTime(nowDate);
                insert(bill); 
                
                FeeBillDetail detail = new FeeBillDetail();
                detail.setId(UniqueNumberUtils.get18UniqueNumber());
        
                /** 根据物业账单模板录入数据 **/
                detail.setBillId(bill.getId());
                detail.setId(UniqueNumberUtils.get18UniqueNumber());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date sdate = null;
                Date edate = null;
                try {
                    sdate = sdf.parse(obj.get(6));
                    edate = sdf.parse(obj.get(7));
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
                detail.setStartDate(sdate);
                detail.setEndDate(edate);
                detail.setPayTime(nowDate);
                detail.setUpdateTime(nowDate);
                detail.setState(Constants.NORMAL_STATE);
                
                int month;
                try {
                    month = getMonthSpace(sdate,edate);
                    detail.setMonth(month);
                    BigDecimal area = house.getArea();
                    
                    detail.setArea(area);
                    detail.setRate(Constants.INIT_RATE);
                    detail.setUnitPrice(Constants.INIT_UNIT_PRICE);
                    
                    BigDecimal money = mul(area, Constants.INIT_RATE ,month ,Constants.GENERATE_WAY_IMPORT);
                    detail.setMoney(money);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                
                detail.setPayWay(Constants.PAY_WAY_HOUTAI);
                detail.setGenerateWay(Constants.GENERATE_WAY_IMPORT);
                int type = Constants.COMPANY_TYPE_PROPERTY;
                detail.setOperatorType(type);
                if (obj.get(9).equals("个人")) {
                    detail.setBillType(PERSON_BILL);
                } else if (obj.get(9).equals("单位")) {
                    detail.setBillType(COMPANY_BILL);
                } else
                    detail.setBillType(NO_BILL);// 发票类型
                
                detail.setBillTitle(obj.get(10));
                detail.setOperator(user.getUsername());
                detail.setOperatorAccount(user.getId());
                
                detailDao.insert(detail);
            }
            flag = Constants.SQL_RESULT_SUCCESS;
        }
        return flag;
    }

    @Override
    public String findBug(String cellId,List<List> list) {
        StringBuffer errorMsg = new StringBuffer();
        String name ="";
        
        if(!list.isEmpty()) {
            Pattern patternBillType = Pattern.compile("^(无|个人|单位)$");//标准发票类型
            
            CellRegion region = null;
            List<CellRegion> regionList = null;
            
            CellBuilding build = null;
            List<CellBuilding> buildList = null;
            
            CellUnit unit = null;
            List<CellUnit> unitList = null;
            
            CellHouse house = null;
            List<CellHouse> houseList = null;
            
            int size = list.size();
            for(int i = 0; i < size; i++) {
                List record = list.get(i);
                
                if (StringUtils.isEmpty((String)record.get(1))) {
                    continue;
                }
                
                region = new CellRegion();
                region.setCellId(cellId);
                region.setName((String) record.get(2));
                regionList = cellRegionService.selectForImport(region);
                if (regionList.size() == Constants.SQL_RESULT_FAILD) {
                    errorMsg.append(("第("+(i+1)+",3)项的区域不属于该小区,"));
                    continue;
                } else {
                    build = new CellBuilding();
                    build.setCellId(cellId);
                    build.setRegionName((String) record.get(2));
                    build.setBuildingName((String) record.get(3));
                    buildList = cellBuildingService.selectForImport(build);
                    if (buildList.size() == Constants.SQL_RESULT_FAILD) {
                        errorMsg.append(("第("+(i+1)+",4)项的楼栋不属于该区域,"));
                        continue;
                    } else {
                        unit = new CellUnit();
                        unit.setCellId(cellId);
                        unit.setRegionName((String) record.get(2));
                        unit.setBuildingName((String) record.get(3));
                        unit.setName((String) record.get(4));
                        unitList = cellUnitService.selectForImport(unit);
                        if (unitList.size() == Constants.SQL_RESULT_FAILD) {
                            errorMsg.append(("第("+(i+1)+",5)项的单元不属于该楼栋,"));
                            continue;
                        } else {
                            house = new CellHouse();
                            house.setCellId(cellId);
                            house.setRegionName((String) record.get(2));
                            house.setBuildingName((String) record.get(3));
                            house.setUnitName((String) record.get(4));
                            name = (String) record.get(5);
                            name = name.substring(0,name.indexOf("."));
                            house.setName(name);
                            houseList = cellHouseService.selectForImport(house);
                            if (houseList.size() == Constants.SQL_RESULT_FAILD) {
                                errorMsg.append(("第("+(i+1)+",6)项的房间不属于该单元,"));
                                continue;
                            }
                        }
                    }
                }
                
                String billType = (String) record.get(9);//发票类型
                if(!org.springframework.util.StringUtils.isEmpty(billType)) {
                    Matcher match = patternBillType.matcher(billType);
                    if(!match.matches()) errorMsg.append(("第("+(i+1)+",10)项的发票类型不符合模版数据,"));
                    continue;
                }
                
                
            }
        } else {
            errorMsg.append("无数据");
        }
        return errorMsg.toString();
    }
    
    public static int getMonthSpace(Date date1, Date date2) throws ParseException {

        int result = 0;
    
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
    
        c1.setTime(date1);
        c2.setTime(date2);
    
        result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
    
        return result == 0 ? 1 : Math.abs(result);
    
    }
    
    public static BigDecimal mul(BigDecimal d1, BigDecimal d2,int month,int rate) {        // 进行乘法运算
         BigDecimal months = new BigDecimal(month);
         BigDecimal rates = new BigDecimal(rate);
         
         return months.multiply(rates).multiply(d1).multiply(d2);
     }

    @Override
    public FeeBillConfig getFeeBillConfigByCellId(String cellId) {
        return dao.getFeeBillConfigByCellId(cellId);
    }

    @Override
    public List<FeeBill> selectPropertyFeeBill(FeeBill record) {
        return dao.selectPropertyFeeBill(record);
    }

	@Override
	public Integer selectByHouseIds(String[] houseIDs) {
		return dao.selectByHouseIds(houseIDs);
	}
}